import './index.scss';
import React, { Component } from 'react'
import services from 'services';
import classNames from 'classnames';
import PageLayout from 'layouts/Page';
import Steps from 'components/Steps';
import Input from 'components/Input';
import Button from 'components/Button';
import Container from 'components/Container';
import PopupCascader from 'rmc-cascader/lib/Popup';
import Cascader from 'rmc-cascader';
import { loadingOn } from 'components/Loading';
import qs from 'qs';

@PageLayout({ classNames: 'page-preorder-steps01', title: '填写接种人信息', showCrmButton: true })
class Page extends Component {
  stepsData = {
    steps: [{}, {}, {}, {}]
  }

  constructor(props) {
    super(props);

    this.state = {
      currentIndex: 0,
      errors: {},
      name: '',
      idcard: '',
      phone: qs.parse(location.href.split('?')[1]).mobile || '',
      queueId: '',
      isConfirmModalVisible: false,
      queueList: []
    };
  }

  componentDidMount() {
    //  默认关闭页面
    this.props.setHeader({
      onBack: () => {
        location.href = 'jzapp://close_web_page';
      }
    });

    services.Preorder.getQueues().then(res => {
      let { data, code } = res.data;

      if (code == 0) {
        this.setState({
          queueList: data.map(item => ({
            label: item.name,
            value: item.id,
            prepayAmount: item.prepayAmount
          })),
          queueId: data.length === 1 ? data[0].id : '' //  set default queue
        })
      }
    });
  }

  back = () => {
    location.href = 'jzapp://close_web_page';
  }

  renderError = (field) => {
    let error = this.state.errors[field];
    return error ? <div className="error">{error}</div> : null;
  }

  resetError = (field) => {
    let newErrors = { ...this.state.errors };
    delete newErrors[field];

    this.setState({
      errors: { ...newErrors }
    })
  }

  handleVaccineChanged = (val) => {
    this.setState({ queueId: val[0] });
  }

  validInfo = () => {
    let { name, queueId, phone, idcard } = this.state;
    let errors = {};

    !queueId && (errors.queueId = '请选择接种城市及疫苗');
    !name && (errors.name = '请输入接种人姓名');
    name.length > 16 && (errors.name = '请输入正确的姓名');
    !idcard && (errors.idcard = '请输入身份证号码');
    idcard && !/(^\d{17}(\d|X|x)$)/.test(idcard) && (errors.idcard = '请输入正确的身份证号码');
    !phone && (errors.phone = '请输入手机号码');
    phone && !/(^\d{11,12}$)/.test(phone) && (errors.phone = '请输入正确的手机号码');

    return Object.keys(errors).length ? this.setErrorsThenReturnFalse(errors) : true;
  }

  setErrorsThenReturnFalse = (errors) => {
    this.setState({
      errors: { ...this.state.errors, ...errors }
    });

    return false;
  }

  toggleConfirmModalVisible = (visible) => {
    this.setState({ isConfirmModalVisible: visible !== undefined ? visible : !this.state.isConfirmModalVisible });
  }

  next = () => {
    if (this.validInfo()) {
      this.requestPreorder();
    }
  }

  requestPreorder = () => {
    loadingOn();
    this.setState({ isRequesting: true });
    services.Preorder.submitPreorder({
      mobile: this.state.phone,
      name: this.state.name,
      idCard: this.state.idcard,
      queueId: this.state.queueId,
    }).then(res => {
      let { data, code, msg } = res.data;
      if (code != 0) return alert(msg);
      this.setState({ order: { ...data } });
      this.toggleConfirmModalVisible(true);
    }).finally(() => {
      this.setState({ isRequesting: false });
    });
  }
  
  pay = () => {
    let { orderNo, queueRecordId } = this.state.order;
    this.toggleConfirmModalVisible(false);
    location.href = `jzapp://wechat_payment?orderId=${orderNo}&recordId=${queueRecordId}&orderType=preorder`;
  }

  render() {
    let {
      currentIndex,
      name,
      phone,
      idcard,
      queueId,
      queueList,
      isConfirmModalVisible,
      isRequesting
    } = this.state;
    let isNextDisabled = [name, queueId, phone, idcard].includes('') || isRequesting;
    let currentSelectedQueueLabel = queueId ? queueList.find(item => item.value === queueId).label : '请选择' ;
    let selected = queueList.find(item => item.value === queueId);

    let cascader = (
      <Cascader
        onChange={this.onPickerChange}
        onScrollChange={this.onScrollChange}
        cols={1}
        data={queueList}
      />
    );

    return (
      <div className={`steps${currentIndex + 1}`}>
        <Steps {...this.stepsData} currentIndex={currentIndex} cantBack />

        <Container>
          <div className="card">
            <div className="row" onClick={this.resetError.bind(this, 'queueId')}>
              {this.renderError('queueId')}
              <div className="label">接种城市及疫苗</div>
              <div className="label-for">
                <PopupCascader
                  cascader={cascader}
                  value={[queueId]}
                  onOk={this.handleVaccineChanged}
                  okText="确定"
                  dismissText="取消"
                  title="选择接种城市"
                >
                  <p className={currentSelectedQueueLabel === '请选择' ? 'placeholder' : ''}>{currentSelectedQueueLabel}</p>
                </PopupCascader>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="row" onClick={this.resetError.bind(this, 'name')}>
              {this.renderError('name')}
              <div className="label">接种人姓名</div>
              <div className="label-for">
                <Input placeholder="请输入接种人姓名" value={name} onChange={val => this.setState({ name: val })} />
              </div>
            </div>

            <div className="row" onClick={this.resetError.bind(this, 'idcard')}>
              {this.renderError('idcard')}
              <div className="label">身份证号</div>
              <div className="label-for">
                <Input placeholder="请输入接种人身份证号" value={idcard} onChange={val => this.setState({ idcard: val })} />
              </div>
            </div>

            <div className="row" onClick={this.resetError.bind(this, 'phone')}>
              {this.renderError('phone')}
              <div className="label">手机号</div>
              <div className="label-for">
                <Input htmlType="tel" placeholder="用于接收疫苗通知及预约接种" value={phone} onChange={val => this.setState({ phone: val })} />
              </div>
            </div>
          </div>

          <Button
            type={`block primary`}
            disabled={isNextDisabled}
            onClick={this.next}
          >{ selected ? `定金:¥${selected.prepayAmount} 立即支付` : '加入排队' }</Button>

          {
            isConfirmModalVisible &&
            <div className="confirm-modal">
              <div className="confirm-modal-mask"></div>
              <div className="confirm-modal-bd">
                <div className="hd">确认付款 <span className="icon-close" onClick={this.toggleConfirmModalVisible.bind(this, false)}></span></div>
                <div className="bd">
                  <h2>¥{selected.prepayAmount}</h2>
                  <ul>
                    <li>
                      <div className="key">接种城市及疫苗：</div>
                      <div className="value">{currentSelectedQueueLabel}</div>
                    </li>
                    <li>
                      <div className="key">接种人姓名：</div>
                      <div className="value">{name}</div>
                    </li>
                    <li>
                      <div className="key">身份证号：</div>
                      <div className="value">{idcard}</div>
                    </li>
                    <li>
                      <div className="key">手机号：</div>
                      <div className="value">{phone}</div>
                    </li>
                  </ul>

                  <Button
                    type={`block primary`}
                    onClick={this.pay}
                  >
                    <span className="icon-wechat"></span>
                    微信支付
                  </Button>
                </div>
              </div>
          </div>
          }
        </Container>
      </div>
    )
  }
}

export default Page;